//
//  OrderMainViewController.m
//  Karaoke
//
//  Created by 蒋 浩锋 on 12-8-12.
//  Copyright (c) 2012年 Jiang Haofeng. All rights reserved.
//

#import "OrderMainViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "CagetoryCell.h"
#import "ServerNetworkCenter.h"
#import "FoodView.h"
#import "MenuObject.h"
#import "UIImageView+WebCache.h"
#import "RoomInfoBarView.h"
#import "OrderedFoodViewController.h"
#import "TempOederCenter.h"
#import "MPFoldTransition.h"
#import "MPFlipTransition.h"
#import "SDWebImageManager.h"

// #import "MPFoldSegue.h

@interface OrderMainViewController () <TempOederCenterDelegate>
{
    __gm_weak GMGridView         *_gmGridView;
    __weak IBOutlet FXLabel      *lblClerkName;
    __weak IBOutlet UITableView  *categoryTblView;
    IBOutlet RoomInfoBarView     *roomInfobar;
    __weak IBOutlet UIScrollView *gridPanentView;
    NSArray                      *foodListArray;
    NSDictionary                 *FoodTypeDict;
    __weak IBOutlet FXLabel      *lblOrderNum;
    NSInteger                    selectedIndex;
    __weak IBOutlet UIImageView  *syLogo;
    __weak IBOutlet UIImageView  *sdLogo;
    BOOL                         isRecommend;
    
    NSArray           *catagoryKeys;
    SDWebImageManager *imageManager;
}

@end

@implementation OrderMainViewController
@synthesize currentBtn;
@synthesize popoverController;
@synthesize dismissDelegate;

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self)
    {
        // Custom initialization
    }
    
    return self;
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    
    selectedIndex = -1;
    
    if (OEM_FLAG == 1)
    {
        sdLogo.hidden = NO;
        syLogo.hidden = YES;
    }
    [TempOederCenter sharedInstance].delegata      = self;
    self.navigationController.navigationBar.hidden = YES;
    [SocketDataHandle sharedInstance].delegate     = self;
    roomInfobar                                    = [[RoomInfoBarView alloc] initWithXib];
    roomInfobar.frame                              = CGRectMake(10.0f, 19, roomInfobar.frame.size.width, roomInfobar.frame.size.height);
    [self.view addSubview:roomInfobar];
    GMGridView *gmGridView = [[GMGridView alloc] initWithFrame:gridPanentView.bounds];
    gmGridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    gmGridView.backgroundColor  = [UIColor clearColor];
    gmGridView.tag              = 0;
    [gridPanentView addSubview:gmGridView];
    _gmGridView                                           = gmGridView;
    _gmGridView.layoutStrategy                            = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutVertical];
    _gmGridView.style                                     = GMGridViewStyleSwap;
    _gmGridView.showFullSizeViewWithAlphaWhenTransforming = NO;
    _gmGridView.itemSpacing                               = 5;
    _gmGridView.minEdgeInsets                             = UIEdgeInsetsMake(5, 5, 5, 5);
    _gmGridView.centerGrid                                = YES;
    _gmGridView.actionDelegate                            = self;
    _gmGridView.dataSource                                = self;
    _gmGridView.delegate                                  = self;
    _gmGridView.showsHorizontalScrollIndicator            = NO;
    imageManager                                          = [[SDWebImageManager alloc]init];
    if (![ServerNetworkCenter sharedInstance].isConnect)
    {
        [[ServerNetworkCenter sharedInstance] initConnect];
    }
    
    //    [[ServerNetworkCenter sharedInstance] sentMsg:rtRoomStateAndInfo:[DataCenter sharedInstance].roomNo, nil];
    //    roomInfobar.lblYiXiaoFei.text = [SocketDataHandle sharedInstance].roomState.XiaoFeiJinE;
    //    roomInfobar.lblZuiDiXiaoFei.text = [SocketDataHandle sharedInstance].roomState.LowLimitMoney;
    //    roomInfobar.lblDingFangRen.text = [SocketDataHandle sharedInstance].roomState.ReserveClerk.length > 0 ? [SocketDataHandle sharedInstance].roomState.ReserveClerk : @"客订";
    lblClerkName.text = [DataCenter sharedInstance].clerkName;
    //    roomInfobar.lblRoomName.text = [DataCenter sharedInstance].roomNo;
    [[ServerNetworkCenter sharedInstance] sentMsg:rtFoodType:@"0", @"100", @"0", [DataCenter sharedInstance].clerkNo, @"", nil];    // Do any additional setup after loading the view.
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_gmGridView reloadData];
    [SocketDataHandle sharedInstance].delegate = self;
}

- (void) viewDidUnload
{
    lblClerkName    = nil;
    categoryTblView = nil;
    FoodTypeDict    = nil;
    gridPanentView  = nil;
    gridPanentView  = nil;
    roomInfobar     = nil;
    lblOrderNum     = nil;
    syLogo          = nil;
    sdLogo          = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [SocketDataHandle sharedInstance].delegate = self;
    lblOrderNum.text                           = [NSString stringWithFormat:@"%d", [SocketDataHandle sharedInstance].tmpSelectFood.foodSet.count];
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (IBAction) btnBackAction:(id)sender
{
    self.view.userInteractionEnabled = NO;
    //    HMGLTransition *transition = [[ClothTransition alloc] init];
    //
    //    [[HMGLTransitionManager sharedTransitionManager] setTransition:transition];
    //    [[HMGLTransitionManager sharedTransitionManager] dismissModalViewController:self];
    //    [self dismissViewControllerWithFoldStyle:MPFoldStyleDefault completion:nil];
    //    [self.dismissDelegate dismiss];
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [FoodTypeDict.allKeys sortedArrayUsingComparator: ^(id obj1, id obj2) {
        if ([obj1 integerValue] > [obj2 integerValue])
        {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue])
        {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }
                      
                      ];
    
    catagoryKeys = [[NSArray alloc]initWithArray:array];
    
    return catagoryKeys.count;
}

#pragma make -category TableView Delegate
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CagetoryCell *cell = (CagetoryCell *)[tableView dequeueReusableCellWithIdentifier:@"categoryCell"];
    
    if ([indexPath row] == selectedIndex)
    {
        cell.selectedImage.hidden = NO;
    }
    else
    {
        cell.selectedImage.hidden = YES;
    }
    
    //    cell.lblFoodTypeName.text = [[FoodTypeDict allValues] objectAtIndex:[indexPath row]];
    cell.lblFoodTypeName.text        = [FoodTypeDict objectForKey:[catagoryKeys objectAtIndex:indexPath.row]];
    cell.lblFoodTypeName.shadowColor = [UIColor clearColor];
    //    cell.catagoryText.font = DEFAULT_FONT(DEFAULT_FONTSIZE + 6);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [catagoryKeys objectAtIndex:indexPath.row];
    NSString *ShowLocate;
    switch (ROOMTYPE.intValue)
    {
        case 0:
            ShowLocate = @"1";
            break;
            
        case 1:
            ShowLocate = @"2";
            break;
            
        case 2:
            ShowLocate = @"3";
            break;
            
        default:
            break;
    }
    if (selectedIndex != indexPath.row)
    {
        [[ServerNetworkCenter sharedInstance] sentMsg:rtFoodList:@"0", key, [DataCenter sharedInstance].priceId, @"0", @"1", [DataCenter sharedInstance].clerkNo, @"", ROOMTYPE, [DataCenter sharedInstance].roomNo, @"0", ShowLocate, @"", nil];
        selectedIndex = indexPath.row;
        [categoryTblView reloadData];
    }
}

#pragma make --SocketData Delegate
- (void) socketDataHandleDidCategory:(NSMutableDictionary *)categoryDict
{
    FoodTypeDict = [[NSDictionary alloc] initWithDictionary:categoryDict];
    [categoryTblView reloadData];
    [self tableView:categoryTblView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
}

- (void) socketDataHandleDidRoomStateAndInfo:(RoomStateAndInfo *)roomStateInfo
{
    roomInfobar.lblYiXiaoFei.text    = roomStateInfo.XiaoFeiJinE;
    roomInfobar.lblZuiDiXiaoFei.text = roomStateInfo.LowLimitMoney;
    roomInfobar.lblDingFangRen.text  = roomStateInfo.ReserveClerk.length > 0 ? roomStateInfo.ReserveClerk : @"客订";
    lblClerkName.text                = [DataCenter sharedInstance].clerkName;
    roomInfobar.lblRoomName.text     = [DataCenter sharedInstance].roomNo;
}

- (void) socketDataHandleDidFoodList:(NSArray *)foodList
{
    if (isRecommend)
    {
        if (foodList.count > 0)
        {
            [self performSegueWithIdentifier:@"showRecommendView" sender:foodList];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有推荐菜品！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            isRecommend = NO;
        }
    }
    else
    {
        if (foodListArray == nil)
        {
            foodListArray = [[NSArray alloc] init];
        }
        
        foodListArray = foodList;
        [_gmGridView reloadData];
        [_gmGridView setContentOffset:CGPointMake(0, 0)];
    }
}

- (NSURL *) GetServerUrl:(NSString *)foodNO imgWidth:(CGFloat)width imgHeigth:(CGFloat)heigth
{
    NSString *serverIP = [[NSUserDefaults standardUserDefaults] stringForKey:@"Server_Ip"];
    NSString *url      = [NSString stringWithFormat:@"http://%@/GetPhoto.aspx?Flag=00&id=%@&width=%.0f&height=%.0f", serverIP, foodNO, width * 2, heigth * 2];
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    return [NSURL URLWithString:url];
}

- (void) showInputView:(UIButton *)sender
{
    currentBtn = sender;
    OKFoodObject *tempFoodObject = [foodListArray objectAtIndex:sender.tag];
    
    for (OKFolioObject *folioObj in[SocketDataHandle sharedInstance].tmpSelectFood.foodSet)
    {
        if ([folioObj.FoodNo isEqualToString:tempFoodObject.No])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
                                                            message:@"您已经点选了该项，如需修改请删除后再点！"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
    }
    
    [self performSegueWithIdentifier:@"showPopView" sender:tempFoodObject];
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showPopView"])
    {
        PopViewController *viewController = segue.destinationViewController;
        viewController.delegate       = self;
        viewController.tempFoodObject = sender;
    }
    else if ([[segue identifier] isEqualToString:@"showRecommendView"])
    {
        RecommendViewController *viewController = segue.destinationViewController;
        viewController.delegate     = self;
        viewController.tempFoodList = sender;
    }
}

- (void) popViewControllerDidConfirm:(PopViewController *)popController
{
    [SocketDataHandle sharedInstance].delegate = self;
    [_gmGridView reloadData];
    lblOrderNum.text = [NSString stringWithFormat:@"%d", [SocketDataHandle sharedInstance].tmpSelectFood.foodSet.count];
    [self.popoverController dismissPopoverAnimated:YES];
}

- (void) popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [SocketDataHandle sharedInstance].delegate = self;
    lblOrderNum.text                           = [NSString stringWithFormat:@"%d", [SocketDataHandle sharedInstance].tmpSelectFood.foodSet.count];
}

// ////////////////////////////////////////////////////////////
#pragma mark GMGridViewDataSource
// ////////////////////////////////////////////////////////////

- (NSInteger) numberOfItemsInGMGridView:(GMGridView *)gridView
{
    return foodListArray.count;
}

- (CGSize) GMGridView:(GMGridView *)gridView sizeForItemsInInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    return CGSizeMake(775, 190);
}

- (GMGridViewCell *) GMGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index
{
    OKFoodObject *obj  = [foodListArray objectAtIndex:index];
    FoodView     *cell = (FoodView *)[gridView dequeueReusableCell];
    
    if (!cell)
    {
        cell                               = [[FoodView alloc] initWithXib];
        cell.foodImage.layer.cornerRadius  = 8;
        cell.foodImage.layer.masksToBounds = NO;
        cell.foodImage.layer.shadowColor   = [UIColor blackColor].CGColor;
        cell.foodImage.layer.shadowOffset  = CGSizeMake(0, 0);
        cell.foodImage.layer.shadowOpacity = 0.5;
        cell.foodImage.backgroundColor     = [UIColor darkGrayColor];
    }
    
    cell.selectedImg.hidden    = YES;
    cell.lblSeleceedNum.hidden = YES;
    
    for (OKFolioObject *tempFolio in[SocketDataHandle sharedInstance].tmpSelectFood.foodSet)
    {
        if ([tempFolio.FoodNo isEqualToString:obj.No])
        {
            cell.selectedImg.hidden    = NO;
            cell.lblSeleceedNum.hidden = NO;
            cell.lblSeleceedNum.text   = [NSString stringWithFormat:@"%d", tempFolio.Quantity];
            break;
        }
    }
    
    cell.lblFoodName.text   = obj.NameChs;
    cell.lblFoodEnName.text = obj.NameEng;
    cell.btnSelect.tag      = index;
    [cell.btnSelect addTarget:self action:@selector(showInputView:) forControlEvents:UIControlEventTouchUpInside];
    cell.FoodPirceAndUnit.text = [NSString stringWithFormat:@"%@/%@", obj.Price, obj.Monad];
    //    cell.snapshotStackView.image = [UIImage imageNamed:@"default_image.jpg"];
//    [cell.foodImage setImageWithURL:[self GetServerUrl:obj.No imgWidth:cell.foodImage.bounds.size.width imgHeigth:cell.foodImage.bounds.size.height] placeholderImage:[UIImage imageNamed:@"PhotoDetailPreview_default"]];
    [cell.foodImage setImageWithURL:[self GetServerUrl:obj.No imgWidth:cell.foodImage.bounds.size.width imgHeigth:cell.foodImage.bounds.size.height] placeholderImage:[UIImage imageNamed:@"PhotoDetailPreview_default"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (image == nil) {
            [cell.foodImage setImage:[UIImage imageNamed:@"default_image.jpg"]];
        }
    }];
    
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //        [cell.snapshotStackView setImageWithURL:[self GetServerUrl:obj.No imgWidth:cell.foodImage.bounds.size.width imgHeigth:cell.foodImage.bounds.size.height]];
    //           });
    
    
    
    
    return cell;
}

- (BOOL) GMGridView:(GMGridView *)gridView canDeleteItemAtIndex:(NSInteger)index
{
    return NO; // index % 2 == 0;
}

// ////////////////////////////////////////////////////////////
#pragma mark GMGridViewActionDelegate
// ////////////////////////////////////////////////////////////

- (void) GMGridView:(GMGridView *)gridView didTapOnItemAtIndex:(NSInteger)position
{
    NSLog(@"Did tap at index %d", position);
}

- (void) GMGridViewDidTapOnEmptySpace:(GMGridView *)gridView
{
    NSLog(@"Tap on empty space");
}

- (void) GMGridView:(GMGridView *)gridView processDeleteActionForItemAtIndex:(NSInteger)index
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirm" message:@"Are you sure you want to delete this item?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete", nil];
    
    [alert show];
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
}

- (IBAction) recommendAction:(id)sender
{
    isRecommend = YES;
    NSString         *ShowLocate;
    SocketDataHandle *sock = [SocketDataHandle sharedInstance];
    switch (sock.roomState.RoomType.intValue)
    {
        case 0:
            ShowLocate = @"1";
            break;
            
        case 1:
            ShowLocate = @"2";
            break;
            
        case 2:
            ShowLocate = @"3";
            break;
            
        default:
            break;
    }
    [[ServerNetworkCenter sharedInstance] sentMsg:rtFoodList:@"0", @"", [DataCenter sharedInstance].priceId, @"0", @"1", [DataCenter sharedInstance].clerkNo, @"", @"0", [DataCenter sharedInstance].roomNo, @"1", ShowLocate, @"", nil];
}

- (void) dismiss:(RecommendViewController *)viewController
{
    [viewController dismissModalViewControllerAnimated:YES];
    isRecommend = NO;
}

@end